package com.imchen.cms.handler;

import com.imchen.cms.exception.CmsException;
import com.imchen.cms.exception.TokenException;
import com.imchen.cms.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;

/**
 * @author imchen
 * @create: 2019-01-14 07:37
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = CmsException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result handleResourceNotFoundException(CmsException e) {
        logger.error(e.getMessage(), e);
        return new Result(e.getCode(), e.getMessage(), "");
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleGlobalException(Exception e) {
        String msg = "No handle exception!";
        logger.error("Global Exception!!! {}", e);
        if (e instanceof org.springframework.dao.DataIntegrityViolationException) {
            msg = "request or post argument error ! please check!";
        } else if (e instanceof org.springframework.web.multipart.MaxUploadSizeExceededException) {
            msg = "Upload file size too large";
        }
        if (e instanceof org.mybatis.spring.MyBatisSystemException) {
            msg ="数据路连接错误，请检查连接信息！";
        }
        return new Result(500, msg, "");
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({IllegalArgumentException.class, MissingServletRequestParameterException.class})
    public Result handleIllegalArgumentException(Exception e) {
        logger.error("请求参数异常：{}", e.getMessage());
        return new Result(1, "参数异常：" + e.getMessage(), "");
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(TokenException.class)
    public Result handleTokenException(TokenException e) {
        return new Result(e.getCode(), e.getMessage(), "");
    }


}
